package com.likerSai;

import java.util.ArrayList;

/**
 * 字符串转换整数
 *
 * @author sun.ye
 * @since 2021-04-28 15:55
 */
public class MyAtoi {
    public static void main(String[] args) {

        int result =  myAtoi("  -122229999999999999999999999999999www");
        System.out.println(result);
    }

    public static int myAtoi(String s){

        int flag = 1;
        char[] chars = s.trim().toCharArray();
        if (chars.length == 0){
            return 0;
        }
        if(!Character.isDigit(chars[0])){
            if (chars[0] == '-'){
                flag = -1;
                chars[0] = '0';
            }else if (chars[0] == '+'){
                chars[0] = '0';
            }else {
                return 0;
            }
        }
        long result = 0L;
        for (char c : chars ) {
            if (Character.isDigit(c)){
                result = result * 10 + Integer.parseInt(String.valueOf(c));
                if (flag * result >= Integer.MAX_VALUE){
                    return Integer.MAX_VALUE;
                }
                if (flag * result <= Integer.MIN_VALUE){
                    return  Integer.MIN_VALUE;
                }
            }else {
                break;
            }
        }

        return (int) (flag * result);
    }
}